package com.gcxy.shop.dao;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gcxy.shop.common.CommonException;
import com.gcxy.shop.common.JdbcUtils;
import com.gcxy.shop.domain.User;



public class UserDao {
	private static Logger logger=LoggerFactory.getLogger(JdbcUtils.class);

	private static User rowMap(ResultSet rs) throws SQLException {
		User user=new User();
		user.setId(rs.getInt("id"));
		user.setUsername(rs.getString("username"));
		user.setUsercode(rs.getString("usercode"));
		user.setPassword(rs.getString("password"));
		return user;
	}//映射器
	public User findBycode(String usercode) {
		Connection conn=JdbcUtils.getConnection();
	    PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			String sql="select * from user where usercode=?";
			ps=conn.prepareStatement(sql);
			ps.setString(1,usercode);
			rs=ps.executeQuery();
			while (rs.next()) {
			return rowMap(rs);
				
			}
		} catch (Exception e) {
		  logger.error(e.getMessage());
		  throw new CommonException();
		}finally {
			JdbcUtils.close(conn, ps, rs);
		}
		
		User user=new User(usercode,"系统管理员","123456");
			return user;
	}

	public void save(User user) {
		//保存注册的信息进入数据库
		Connection conn=JdbcUtils.getConnection();
	    PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			String sql="insert into user(username,password,usercode) values(?,?,?)";
			ps=conn.prepareStatement(sql);
			ps.setString(1,user.getUsername());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getUsercode());
			int ret=ps.executeUpdate();
			if(ret<=0) {
				throw new CommonException("插入错误");
			}
			logger.debug("插入数据成功");
			logger.debug("{}---{}----{}",user.getUsercode(),user.getPassword(),user.getUsername());
		} catch (Exception e) {
		  logger.error(e.getMessage());
		  throw new CommonException();
		}finally {
			JdbcUtils.close(conn, ps, rs);
		}
	}

	public void update(User user) {
		// 修改数据库表
		Connection conn=JdbcUtils.getConnection();
	    PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			String sql="update user set username=?,password=? where usercode=?";
			ps=conn.prepareStatement(sql);
			ps.setString(1,user.getUsername());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getUsercode());
			logger.debug("执行");
			
			
			if(ps.executeUpdate()<1) {
				throw new CommonException("修改数据错误");
			}
			logger.debug("修改数据成功");
			logger.debug("{}---{}----{}",user.getUsername(),user.getPassword(),user.getUsercode());
			
		} catch (Exception e) {
		  logger.error(e.getMessage());
		  throw new CommonException();
		}finally {
			JdbcUtils.close(conn, ps, rs);
		}
	}

	}